<template>
  <div class="profile-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon class="title-icon"><User /></el-icon>
          个人中心
        </h1>
        <p class="page-subtitle">管理您的个人信息和账户设置</p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="profile-content">
      <!-- 左侧用户信息卡片 -->
      <div class="profile-sidebar">
        <div class="user-profile-card">
          <div class="avatar-section">
            <div class="avatar-container">
              <el-avatar :size="120" :src="loginStore.userInfo?.avatar" @error="profileStore.onAvatarError">
                <el-icon size="60"><User /></el-icon>
              </el-avatar>
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="profileStore.handleAvatarUpload"
                accept="image/*"
              >
                <div class="avatar-overlay">
                  <el-icon><Camera /></el-icon>
                  <span>更换头像</span>
                </div>
              </el-upload>
            </div>
          </div>
          
          <div class="user-info">
            <h2 class="username">{{ loginStore.userInfo?.username || '未设置' }}</h2>
            <div class="user-role">
              <el-tag :type="profileStore.getRoleTagType(loginStore.userInfo?.role)" size="large" effect="dark">
                <el-icon><Star /></el-icon>
                {{ profileStore.getRoleName(loginStore.userInfo?.role) }}
              </el-tag>
            </div>
            <div class="user-meta">
              <div class="meta-item">
                <el-icon><UserFilled /></el-icon>
                <span>ID: {{ loginStore.userInfo?.id || 'N/A' }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>注册于 {{ profileStore.formatDate(loginStore.userInfo?.create_time) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 账户统计 -->
        <div class="stats-card">
          <h3 class="stats-title">
            <el-icon><TrendCharts /></el-icon>
            账户统计
          </h3>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ profileStore.formatDate(loginStore.userInfo?.update_time) }}</div>
                <div class="stat-label">最后更新</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon><SwitchButton /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ loginStore.userInfo?.login_count || 0 }}</div>
                <div class="stat-label">登录次数</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="profile-main">
        <!-- 个人信息编辑 -->
        <div class="info-card">
          <div class="card-header">
            <div class="header-left">
              <h3 class="card-title">
                <el-icon><Edit /></el-icon>
                个人信息
              </h3>
              <p class="card-subtitle">管理您的基本信息</p>
            </div>
          </div>

          <div class="card-content">
            <el-form :ref="setFormRef" :model="form" :rules="formRules" label-position="top" class="profile-form">
              <div class="form-section">
                <h4 class="section-title">基本信息</h4>
                <el-row :gutter="24">
                  <el-col :span="12">
                        <el-form-item label="用户名" prop="username" required>
                          <el-input 
                            v-model="form.username" 
                            placeholder="请输入用户名" 
                            size="large"
                            prefix-icon="User"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                    <el-form-item label="邮箱" prop="email" required>
                      <el-input 
                        v-model="form.email" 
                        placeholder="请输入邮箱" 
                        size="large"
                        prefix-icon="Message"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="手机号" prop="phone" required>
                      <el-input 
                        v-model="form.phone" 
                        placeholder="请输入手机号" 
                        size="large"
                        prefix-icon="Phone"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="角色">
                      <el-input 
                        :value="profileStore.getRoleName(loginStore.userInfo?.role)" 
                        disabled
                        size="large"
                        prefix-icon="Star"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

         <div class="form-section">
           <h4 class="section-title">
             <el-icon><Lock /></el-icon>
             密码设置
           </h4>
           <el-row :gutter="24">
             <el-col :span="12">
               <el-form-item label="新密码" prop="password">
                 <el-input 
                   v-model="form.password" 
                   type="password" 
                   placeholder="不修改请留空" 
                   show-password 
                   size="large"
                   prefix-icon="Lock"
                 />
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="确认密码" prop="password_confirm">
                 <el-input 
                   v-model="form.password_confirm" 
                   type="password" 
                   placeholder="再次输入新密码" 
                   show-password 
                   size="large"
                   prefix-icon="Lock"
                 />
               </el-form-item>
             </el-col>
           </el-row>
         </div>

              <div class="form-actions">
                <el-button type="primary" size="large" :loading="profileStore.submitting" @click="submitForm">
                  <el-icon><Check /></el-icon>
                  保存修改
                </el-button>
                <el-button size="large" @click="resetForm">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </div>
            </el-form>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  User, Lock, Message, Phone, Check, Refresh, Edit, Close, 
  Camera, Star, UserFilled, Calendar, TrendCharts, Clock, 
  SwitchButton 
} from '@element-plus/icons-vue'
import { useProfileStore } from '@/stores/profile/profileStore'
import { useLoginStore } from '@/stores/login/loginStore'

// 状态定义
const profileStore = useProfileStore()
const loginStore = useLoginStore()
const formRef = ref()

// 表单数据
const initialFormData = {
  username: '',
  email: '',
  phone: '',
  avatar: '',
  password: '',
  password_confirm: ''
}

const form = reactive({ ...initialFormData })

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^\d{11}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
  ],
  password: [
    { 
      validator: (_r, v, cb) => {
        if (v && v.length < 6) return cb(new Error('密码至少6位'))
        cb()
      }, 
      trigger: ['blur', 'change'] 
    }
  ],
  password_confirm: [
    { 
      validator: (_r, v, cb) => {
        if (form.password && v !== form.password) return cb(new Error('两次密码不一致'))
        cb()
      }, 
      trigger: ['blur', 'change'] 
    }
  ]
}

// 设置表单引用
const setFormRef = (el) => {
  formRef.value = el
}

// 重置表单
const resetForm = () => {
  Object.assign(form, { ...initialFormData })
  loadUserInfo()
}

// 加载用户信息到表单
const loadUserInfo = () => {
  const user = loginStore.userInfo
  if (user) {
    form.username = user.username || ''
    form.email = user.email || ''
    form.phone = user.phone || ''
    form.avatar = user.avatar || ''
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) {
    console.error('formRef 不存在')
    return
  }
  
  const valid = await formRef.value.validate()
  if (!valid) {
    console.error('表单验证失败')
    return
  }

  const payload = {
    username: form.username,
    email: form.email,
    phone: form.phone
  }
  
  if (form.avatar && form.avatar.trim()) {
    payload.avatar = form.avatar.trim()
  }
  
  if (form.password) {
    payload.password = form.password
    payload.password_confirm = form.password_confirm
  }

  await profileStore.updateProfile(payload)
  
  // 清空密码字段
  form.password = ''
  form.password_confirm = ''
}

// 生命周期
onMounted(() => {
  profileStore.loadUserInfo()
  loadUserInfo()
})
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

// 主容器
.profile-container {
  @include page-container;

  // 页面标题
  .page-header {
    @include page-header;
  }

  // 主要内容区域
  .profile-content {
    display: grid;
    grid-template-columns: 320px 1fr;
    gap: 24px;
    max-width: 1200px;
    margin: 0 auto;
    align-items: start;

    // 左侧边栏
    .profile-sidebar {
      display: flex;
      flex-direction: column;
      gap: 20px;

      // 用户信息卡片
      .user-profile-card {
        @include card-style;
        padding: 24px;
        text-align: center;
        position: relative;
        overflow: hidden;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          height: 3px;
          background: $primary-color;
        }

        .avatar-section {
          margin-bottom: 20px;

          .avatar-container {
            position: relative;
            display: inline-block;

            .avatar-uploader {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              border-radius: 50%;
              overflow: hidden;

              :deep(.el-upload) {
                width: 100%;
                height: 100%;
                border: none;
                background: transparent;
              }
            }

            .avatar-overlay {
              position: absolute;
              bottom: 0;
              right: 0;
              background: rgba(0, 0, 0, 0.7);
              color: $white;
              padding: 6px 10px;
              border-radius: 4px;
              font-size: 12px;
              cursor: pointer;
              display: flex;
              align-items: center;
              gap: 4px;
              transition: all 0.3s;
              opacity: 0;
              pointer-events: none;
            }

            &:hover .avatar-overlay {
              opacity: 1;
            }
          }
        }

        .user-info {
          text-align: center;

          .username {
            font-size: 20px;
            font-weight: 600;
            color: $text-color;
            margin: 0 0 12px 0;
          }

          .user-role {
            margin-bottom: 16px;
          }

          .user-meta {
            display: flex;
            flex-direction: column;
            gap: 6px;

            .meta-item {
              display: flex;
              align-items: center;
              justify-content: center;
              gap: 6px;
              color: $text-color-secondary;
              font-size: 14px;
            }
          }
        }
      }

      // 统计卡片
      .stats-card {
        @include card-style;
        padding: 20px;

        .stats-title {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 16px;
          font-weight: 600;
          color: $text-color;
          margin: 0 0 17px 0;
        }

        .stats-grid {
          display: flex;
          flex-direction: column;
          gap: 12px;

          .stat-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 30px 12px;
            background: $background-color;
            border-radius: 6px;
            transition: all 0.3s;

            &:hover {
              background: $gray-200;
            }

            .stat-icon {
              width: 32px;
              height: 32px;
              border-radius: 6px;
              background: $primary-color;
              display: flex;
              align-items: center;
              justify-content: center;
              color: $white;
              font-size: 16px;
            }

            .stat-content {
              flex: 1;

              .stat-value {
                font-size: 14px;
                font-weight: 600;
                color: $text-color;
                margin-bottom: 2px;
              }

              .stat-label {
                font-size: 12px;
                color: $text-color-placeholder;
              }
            }
          }
        }
      }
    }

    // 右侧主内容
    .profile-main {
      display: flex;
      flex-direction: column;
      gap: 24px;
      min-height: 100%;

      // 信息卡片
      .info-card {
        @include card-style;
        overflow: hidden;

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20px 24px;
          background: $background-color;
          border-bottom: 1px solid $border-color;

          .header-left {
            flex: 1;

            .card-title {
              display: flex;
              align-items: center;
              gap: 8px;
              font-size: 18px;
              font-weight: 600;
              color: $text-color;
              margin: 0 0 4px 0;
            }

            .card-subtitle {
              font-size: 14px;
              color: $text-color-secondary;
              margin: 0;
            }
          }
        }

        .card-content {
          padding: 24px;

          // 表单样式
          .profile-form {
            max-width: none;

            .form-section {
              margin-bottom: 24px;

              &:last-child {
                margin-bottom: 0;
              }

              .section-title {
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 16px;
                font-weight: 600;
                color: $text-color;
                margin: 0 0 16px 0;
                padding-bottom: 8px;
                border-bottom: 1px solid $border-color;
              }
            }

            .form-actions {
              display: flex;
              justify-content: flex-start;
              gap: 12px;
              margin-top: 24px;
              padding-top: 16px;
              border-top: 1px solid $border-color;
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .profile-container .profile-content {
    grid-template-columns: 1fr;
    gap: 20px;

    .profile-sidebar {
      order: 2;
    }

    .profile-main {
      order: 1;
    }
  }
}

@media (max-width: 768px) {
  .profile-container {
    padding: 16px;

    .page-header .header-content .page-title {
      font-size: 24px;
    }

    .profile-content .profile-main .info-card {
      .card-header {
        flex-direction: column;
        gap: 12px;
        align-items: stretch;
      }

      .card-content .profile-form .form-actions {
        flex-direction: column;
      }
    }
  }
}

// Element Plus 组件样式覆盖
:deep(.el-form-item) {
  margin-bottom: 20px;

  .el-form-item__label {
    font-weight: 500;
    color: $text-color;
    font-size: 14px;
    padding-bottom: 8px;
  }
}

// 使用Element Plus默认样式，不进行自定义覆盖

:deep(.el-button) {
  @include button-style;

  &.el-button--primary {
    background-color: $primary-color;
    border-color: $primary-color;

    &:hover {
      background-color: #337ecc;
    }
  }
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-avatar) {
  border: 2px solid $white;
  box-shadow: $shadow-light;
}
</style>




